<?php

namespace app\home\controller;

use app\home\model\Idfa724Model;
use app\home\model\Order;
use app\home\service\NotifyService;
use app\home\service\OrderService;
use Exception;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\Db;
use think\helper\hash\Md5;
use think\Loader;
use think\Model;
use think\Request;
use think\response\Json;

class Pay800040 extends BasePay
{

    public function __construct()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 
    }

    public function code()
    {
        Loader::import('jwt.JWT');
        Loader::import('jwt.Key');

        $key = "b3B04jNvivFncwZHFEPTCAnqVfCugYkwo3LWPGWR6jU=";
        // $token = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIzMmEzZWZhOGNjZmQ0ZTc0OGZiNzY1ODFkMjE5ODlhYyIsImFwcElkIjoiMTc5NDk4NDk5NDcwODY1NjEyOCIsInVzZXJJZCI6IjMyYTNlZmE4Y2NmZDRlNzQ4ZmI3NjU4MWQyMTk4OWFjIiwic2hvcElkIjoxMDgsImFjY2Vzc1Rva2VuIjoibUFLY0FhbWMvaXptWGFhd0dZWHJZZ1V3ZUtVQncwYU03VnhyNWRtbFhZUjJHdEJTR2dEbkJjQWZ6TU0vajNHcCIsImV4cCI6MTcyMDM0OTk1NH0.e2j6P4fJ4bOJGsxNFie11bCQSXirfJdsZPRDA650vzQ';

        try {
            $params = Request::instance()->param();

            $decoded = JWT::decode($params['code'], new Key($key, 'HS256'));
            // 打印解密后的数据
            exit(json_encode($decoded));
        } catch (Exception $e) {
            // 如果解密失败，可能是因为Token无效或过期
            echo $e->getMessage();
            die;
        }
    }

    
    public function order()
    {
        parent::order();
        $data_Arr['code'] = 'success';
        $params = Request::instance()->param();

        $json_string = file_get_contents(env('PLATFORM.USD'));
        $config = json_decode($json_string, true);
        $usd  = $config[$this->order_array['goods_id']];
        if(empty($usd)){
            mylog('计费点对应的美元金额找不到');
            throw new \Exception('计费点对应的美元金额找不到');
        }

        $return['orderId'] = $this->order_array['id'];
        $return['amount'] = (int)ceil($usd['Mpay'])*100;
        $return['goods_name'] = $this->order_array['goods_name'];
        $return['goods_id'] = $this->order_array['goods_id'];

        exit(json_encode(['code'=>1,'msg'=>'','data'=>$return]));
    }

    public function token()
    {
        Loader::import('jwt.JWT');
        Loader::import('jwt.Key');
        // 配置JWT
        $key = 'b3B04jNvivFncwZHFEPTCAnqVfCugYkwo3LWPGWR6jU='; // 替换为你的密钥
        $aqppId = '1794984994708656128';
        $data =  [
            'count' => 1,
            'gameCurrencyPrice' => 100,
            'itemKey' => '10001',
            'itemName' => 'test'
        ];
        // 构建payload
        $payload = array(
            "iss" => '',
            "aud" => '',
            "iat" => time(),
            "nbf" => time(),
            "exp" => time()+60*5,
            "data" => $data
        );
        $jwt = JWT::encode($payload, $key, "HS256");//根据参数生成了 token
        $url = 'https://sky-api-dev.war6sky.com/p/token/game-center/uniplay/game/payOrderItem';
        $header =  array(
            "Content-type: application/json",
            // "GAuthorization: ".$jwt,
            "GAuthorization: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI2OTU2OTRjNDg1NTM0YzM5ODUxYWZhZDVjYjhhYjRjNCIsImFwcElkIjoiMTc5NDk4NDk5NDcwODY1NjEyOCIsInVzZXJJZCI6IjY5NTY5NGM0ODU1MzRjMzk4NTFhZmFkNWNiOGFiNGM0Iiwic2hvcElkIjoxMDgsImFjY2Vzc1Rva2VuIjoiMTkyanl4VG92WVVXVFpJSThWTEc5QWFiNWQ4RGZDc1dIODNGQlhTaC9xcmM5M24xUGtqUDFnb3FZeW9BeHp2cyIsImV4cCI6MTcyMTAxNjE2NX0.iGsL3R17DZUub2x3Fi27vnlhHjSiLG7qlBU0q6BSLz0",
            "appId: ".$aqppId
        );
        // var_dump($jwt);
        $Res = $this->curl($url,$data,$header);
        var_dump($Res);
        die;
    }

    public function notify()
    {
        parent::notify();
        $params = Request::instance()->param();
        $header = Request::instance()->header();
        mylog($header);
        mylog($params);
        try{
            //保存第三方单号
            $tradeLog = (new \app\home\model\TradeLog)->where(['id'=>$params['rechargeOrderNo']])->find();
            if (empty($tradeLog)) {
                throw new \Exception('订单不存在');
            }
            $tradeLog->transactionID = $params['payNo'];
            $tradeLog->save();
            //TODO
            if ($tradeLog['goods_id'] != $params['itemKey']) {
                throw new \Exception('计费点不一致' . ' 传参:' .  $params['itemKey'] . ' 实际:' . $tradeLog['goods_id']);
            }
            if ($tradeLog["status"] == OrderService::PAY_STATUS_PAID) {
                mylog("800040 订单已经处理过了 订单id".$tradeLog['id']);
                exit('success');
            }
            // 发货
            $notifyService = new NotifyService();
            if($notifyService->notifyProcess($tradeLog) == false){
                throw new \Exception('notifyProcess false');
            }
            exit('success');
        }catch(\Exception $exception){
            mylog('Pay800040-error:'.$exception->getMessage().' line:'.$exception->getLine().' file:'.$exception->getFile());
            return "error";
        }
    }
    /**
     * @param $url
     * @param null $body
     * @return bool|string
     * @throws Exception
     */
    protected function curl($url, $body, $header)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS,  json_encode($body));
        //TODO 证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        if ($error = curl_error($ch)) {
            mylog("800040error");
            mylog($error);
            die($error);
        }
        curl_close($ch);
        mylog($response);
        return $response;
    }
}
